// views/CategoryManagement.vue
<template>
  <div class="category-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品分类管理</span>
          <el-button type="primary" @click="handleAdd(null)">添加一级分类</el-button>
        </div>
      </template>

      <div class="content-layout">
        <!-- 分类树形结构 -->
        <div class="category-tree">
          <el-tree
            ref="treeRef"
            :data="categoryTree"
            :props="{
      label: 'name',  // 使用name作为显示文本
      children: 'children'
    }"
            node-key="categoryId"
            :expand-on-click-node="false"
            default-expand-all
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <div class="node-content">
                  <span>{{ data.name }}</span>
                  <el-tag
                    :type="data.status === 1 ? 'success' : 'danger'"
                    size="small"
                  >
                    {{ data.status === 1 ? '正常' : '禁用' }}
                  </el-tag>
                </div>
                <span class="actions">
          <el-button
            v-if="data.status === 1"
            type="primary"
            link
            @click="handleAdd(data)"
          >
            添加子分类
          </el-button>
          <el-button
            v-if="data.status === 1"
            type="primary"
            link
            @click="handleEdit(data)"
          >
            编辑
          </el-button>
          <el-button
            v-if="data.status === 1"
            type="danger"
            link
            @click="handleDelete(node, data)"
          >
            删除
          </el-button>
        </span>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑分类' : '添加分类'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="categoryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item
          v-if="categoryForm.parent_id !== null"
          label="父级分类"
        >
          <span>{{ parentCategoryName }}</span>
        </el-form-item>

        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="categoryForm.name"
            placeholder="请输入分类名称"
          />
        </el-form-item>

        <el-form-item label="排序" prop="sort_order">
          <el-input-number
            v-model="categoryForm.sort_order"
            :min="1"
            :max="999"
            placeholder="请输入排序号"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="categoryForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// API基础路径
const baseURL = '/categories'

// 状态变量
const treeRef = ref(null)
const categoryTree = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const parentCategoryName = ref('')

// 表单相关
const formRef = ref(null)
const categoryForm = reactive({
  categoryId: null,
  parentId: null, // 改为parentId
  name: '',
  status: 1,
  sortOrder: 1, // 改为sortOrder
  parent: false // 改为parent
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  sort_order: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 初始化数据
const loadCategoryTree = async () => {
  try {
    const response = await axios.get('/categories/all')
    categoryTree.value = buildTree(response.data)
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 构建树形结构
const buildTree = (categories, parentId = null) => {
  if (!Array.isArray(categories)) return []

  return categories
    .filter(item => {
      // 使用正确的parentId字段
      return item && Number(item.parentId) === (parentId || 0)
    })
    .map(item => ({
      ...item,
      // 重命名字段以匹配后端
      label: item.name,
      children: buildTree(categories, item.categoryId)
    }))
    .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
}

// 添加分类
const handleAdd = (data) => {
  isEdit.value = false
  Object.assign(categoryForm, {
    categoryId: null,
    parentId: data ? data.categoryId : 0,
    name: '',
    status: 1,
    sortOrder: 1,
    parent: false
  })
  parentCategoryName.value = data ? data.name : '无'
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (data) => {
  isEdit.value = true
  Object.assign(categoryForm, {
    categoryId: data.categoryId,
    parentId: data.parentId,
    name: data.name,
    status: data.status,
    sortOrder: data.sortOrder,
    parent: data.parent
  })
  const parentNode = findParentNode(categoryTree.value, data.categoryId)
  parentCategoryName.value = parentNode ? parentNode.name : '无'
  dialogVisible.value = true
}

// 查找父节点
const findParentNode = (tree, categoryId) => {
  for (const node of tree) {
    if (node.children) {
      const parent = node.children.find(child => child.categoryId === categoryId)
      if (parent) return node
      const result = findParentNode(node.children, categoryId)
      if (result) return result
    }
  }
  return null
}

// 删除分类
const handleDelete = (node, data) => {
  ElMessageBox.confirm(
    '确定要删除该分类吗？此操作将无法恢复。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await axios.delete(`/categories/delete/${data.categoryId}`)
      ElMessage.success('删除成功')
      loadCategoryTree()
    } catch (error) {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构造符合后端要求的数据格式
        const submitData = {
          categoryId: categoryForm.categoryId,
          parentId: categoryForm.parentId || 0,
          name: categoryForm.name,
          status: categoryForm.status,
          sortOrder: categoryForm.sortOrder || 1,
          parent: !categoryForm.parentId
        }

        if (isEdit.value) {
          await axios.put(
            `${baseURL}/${submitData.categoryId}`,
            submitData
          )
          ElMessage.success('更新成功')
        } else {
          await axios.post(`${baseURL}/create`, submitData)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        loadCategoryTree()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 获取子分类
// const loadSubCategories = async (parentId) => {
//   try {
//     const response = await axios.get(`${baseURL}/${parentId}`)
//     return response.data
//   } catch (error) {
//     console.error('获取子分类失败:', error)
//     ElMessage.error('获取子分类失败')
//     return []
//   }
// }

// 初始化
onMounted(() => {
  loadCategoryTree()
})
</script>

<style scoped>
.category-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-layout {
  display: flex;
  gap: 20px;
}

.category-tree {
  flex: 1;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.actions {
  display: flex;
  gap: 8px;
}
</style>
